//
//  HTPlayerViewController.m
//  HeartTravel
//
//  Created by lanou on 15/10/29.
//  Copyright © 2015年 陈文杰. All rights reserved.
//

#import "HTPlayerViewController.h"
#import "HTPlayerManager.h"
#import "HTSongModel.h"
#import "NSTimer+HTTimer.h"

@interface HTPlayerViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *discImg;
@property (weak, nonatomic) IBOutlet UIButton *playButton;
@property (weak, nonatomic) IBOutlet UIButton *nextButton;
@property (weak, nonatomic) IBOutlet UIButton *beforeButton;
@property (weak, nonatomic) IBOutlet UISlider *progressSlider;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UILabel *artistLabel;
@property (weak, nonatomic) IBOutlet UILabel *startTimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *finishTimeLabel;
@property (weak, nonatomic) IBOutlet UIImageView *needleView;

@property (nonatomic, strong) NSTimer *timer;

@property (nonatomic, strong) NSMutableArray *musicURLArr;
//@property (nonatomic, strong) HTPlayerManager *manager;

@end

@implementation HTPlayerViewController
+ (instancetype)sharePlayer {
    
    static HTPlayerViewController *playerVC = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        playerVC = [[HTPlayerViewController alloc] init];
    });
    return playerVC;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.view.backgroundColor = [UIColor colorWithRed:0.781 green:1.000 blue:0.950 alpha:1.000];
    [_playButton setBackgroundImage:[UIImage imageNamed:@"高亮播放"] forState:(UIControlStateSelected)];
    [_beforeButton setBackgroundImage:[UIImage imageNamed:@"高亮上一曲"] forState:(UIControlStateHighlighted)];
    [_nextButton setBackgroundImage:[UIImage imageNamed:@"高亮下一曲"] forState:UIControlStateHighlighted];
    [_progressSlider setThumbImage:[UIImage imageNamed:@"player-progress-point@2x"] forState:(UIControlStateNormal)];
    [_progressSlider setThumbImage:[UIImage imageNamed:@"player-progress-point-h@2x"] forState:(UIControlStateHighlighted)];
    _needleView.layer.anchorPoint = CGPointMake(0.9, 0.5);
    
    [self setPlayerInfo];
    
    _timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(timeChange) userInfo:nil repeats:YES];
//    [_timer fire];
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
}

- (void)setPlayerInfo {
    
    HTSongModel *model = self.songsArr[self.selectedIndexPath.row];
    _titleLabel.text = model.name;
    _artistLabel.text = [model.singerName stringByAppendingString:[NSString stringWithFormat:@"%@%@",@"--",model.albumName]];
    
    [self addMusicURL];
    [[HTPlayerManager shareManager] setManagerMusicArray:self.musicURLArr];
    [[HTPlayerManager shareManager] playWithIndex:self.selectedIndexPath.row];
}

#pragma 添加音乐url
- (void)addMusicURL {
    
    self.musicURLArr = [NSMutableArray arrayWithCapacity:0];
    for (HTSongModel *model in self.songsArr) {
        if (model.url.length == 0) {
           model.url = @"http://om32.alicdn.com/1/169/7169/278716/3133260_139714_l.m4a?auth_key=ca43a5f971bb6187b2629db56d17d0d1-1446336000-0-null";
            NSLog(@"无歌曲");
        }

        [self.musicURLArr addObject:model.url];
    }
}

// 拖动进度条,改变播放的时间
- (IBAction)handleDragSliderAction:(UISlider *)sender {
    
    [_timer pauseTimer];
    
    NSTimeInterval newTime = [HTPlayerManager shareManager].finishTime * sender.value;
    [[HTPlayerManager shareManager] seekToTime:newTime];
    
    [_timer resumeTimer];
}


// 播放和暂停
- (IBAction)handlePlayButtonAction:(id)sender {
    
    _playButton.selected = !_playButton.selected;
    [[HTPlayerManager shareManager] playAndPause];
    if (_playButton.selected == YES) {
//    if ([HTPlayerManager shareManager].avPlayer.rate == 0) {
        NSLog(@"暂停");
        _playButton.selected = YES;
        [_timer pauseTimer];
        [UIView animateWithDuration:1 animations:^{
            _needleView.transform = CGAffineTransformMakeRotation(-M_PI/180*30);
        } completion:nil];
    } else {
        NSLog(@"播放");
        _playButton.selected = NO;
        [_timer resumeTimer];
        [UIView animateWithDuration:1 animations:^{
            _needleView.transform = CGAffineTransformMakeRotation(0);
        } completion:nil];
    }
    
}
// 上一曲
- (IBAction)handleBeforeButtonAction:(id)sender {
    
    NSLog(@"上一曲");
    [[HTPlayerManager shareManager] beforeMusic];
    NSInteger row = [HTPlayerManager shareManager].playIndex;
    
    HTSongModel *model = _songsArr[row];
    _titleLabel.text = model.name;
    _artistLabel.text = [model.singerName stringByAppendingString:[NSString stringWithFormat:@"%@%@",@"--",model.albumName]];
}
// 下一曲
- (IBAction)handleNextButtonAction:(id)sender {
    
    NSLog(@"下一曲");
    [[HTPlayerManager shareManager] nextMusic];
    NSInteger row = [HTPlayerManager shareManager].playIndex;
    
    HTSongModel *model = _songsArr[row];
    _titleLabel.text = model.name;
    _artistLabel.text = [model.singerName stringByAppendingString:[NSString stringWithFormat:@"%@%@",@"--",model.albumName]];
    
}
// 返回上个界面
- (IBAction)handleReturnButtonAction:(id)sender {
    
//    [[HTPlayerManager shareManager] stop];
    [self dismissViewControllerAnimated:YES completion:^{
    }];
}
// 计时器
- (void)timeChange {
    
    [UIView animateWithDuration:3 animations:^{
        
        _discImg.transform = CGAffineTransformRotate(_discImg.transform, M_PI);
    } completion:nil];

    // 设置timeLabel显示时间
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSUInteger min = [HTPlayerManager shareManager].finishTime / 60;
        NSUInteger sec = [HTPlayerManager shareManager].finishTime - min * 60;
        _startTimeLabel.text = @"00:00";
        _finishTimeLabel.text = [NSString stringWithFormat:@"%02lu:%02lu", min, sec];
    });
    
    NSUInteger smin = [HTPlayerManager shareManager].currentTime / 60;
    NSUInteger ssec = [HTPlayerManager shareManager].currentTime - smin * 60;
    _startTimeLabel.text = [NSString stringWithFormat:@"%02lu:%02lu", smin, ssec];
    
    NSUInteger remainingtime = [HTPlayerManager shareManager].finishTime - [HTPlayerManager shareManager].currentTime;
    NSUInteger fmin = remainingtime / 60;
    NSUInteger fsec = remainingtime - fmin * 60;
    _finishTimeLabel.text = [NSString stringWithFormat:@"%02lu:%02lu", fmin, fsec];
    
    // 设置进度条
    _progressSlider.minimumValue = 0;
    _progressSlider.maximumValue = 1;
    _progressSlider.value = [HTPlayerManager shareManager].currentTime/(float)[HTPlayerManager shareManager].finishTime;
    
    if ([HTPlayerManager shareManager].currentTime == [HTPlayerManager shareManager].finishTime && ([HTPlayerManager shareManager].finishTime != 0|| [HTPlayerManager shareManager].currentTime != 0)) {
        [self handleNextButtonAction:_nextButton];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
